package cn.wolfcode.wolf2w.interceptor;


import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 用户登录效验
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 解决拦截器跨域问题
        /**
         * instanceof判断左边对象是否为右边类的实例
         * String aa = "xxxx"
         * aa instanceof String
         */
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod mh = (HandlerMethod)handler;
        //登录效验
        String token = request.getHeader("token");
        UserInfo userInfo = userInfoRedisService.findUserInfoByToken(token);
        // 判断当前请求印射方法是否贴有@RequireLogin标签
        if(mh.hasMethodAnnotation(RequireLogin.class)) {
            if (userInfo == null) {
                //没有登录，返回没有登录结果提示
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        return true;
    }

}
